# -*- coding: UTF-8 -*-

import datetime
import sys
import time
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct, FLOAT
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger


__all__ = ['AuditApiRecord']

class AuditApiRecord(Base, SessionMixin):
    '''
    平台api接口调用记录表
    '''
    __tablename__ = "audit_api_record"
    user_name = Column(String(32),index=True, nullable=False, comment='用户名称')
    user_ip = Column(String(24), nullable=False, comment='用户ip')
    user_agent = Column(String(256), comment='用户工具')
    path = Column(String(128), index=True, nullable=False, comment='接口路径')
    method = Column(String(8), index=True, nullable=False, comment='接口方法')
    url = Column(String(256), nullable=False, comment='完整url')
    request_text = Column(String(256), comment='请求体文本')
    response_text = Column(String(256), comment='响应体文本')
    response_code = Column(String(8), comment='响应体文本')
    x_trace_id = Column(String(64), index=True, comment='链路跟踪id')
    create_time = Column(DateTime, default=datetime.datetime.now, comment="创建时间")
    comment = Column(String(256), nullable=True, comment='任务说明')

    __table_args__ = (
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic'
        }
    )

    def __repr__(self):
        return f"<name={self.user_name}, path:{self.path}'>"

    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }
        return result

